import wepy from 'wepy'

export default class extends wepy.mixin {
  data = {
    // 订单列表
    orderList: [],
    // 收货地址
    addressInfo: null,
    // 是否登录
    islogin: false
  }

  onLoad() {
    // 读取收货地址
    this.addressInfo = wepy.getStorageSync('address') || null
    // 获取被选中的商品列表
    this.orderList = wepy.getStorageSync('cart').filter(item => item.isCheck)
  }

  methods = {
    // 选择收货地址
    async chooseAddress() {
      const res = await wepy.chooseAddress().catch(err => err)
      if (res.errMsg !== 'chooseAddress:ok') {
        return wepy.baseToast('选择收货地址失败!')
      }
      this.addressInfo = res
      // 替换本地保存的地址
      wepy.setStorageSync('address', res)
      this.$apply()
    },

    // 获取用户信息
    async getUserInfo(userInfo) {
      // console.log(userInfo)
      // 判断是否获取用户信息失败
      if (userInfo.detail.errMsg !== 'getUserInfo:ok') {
        return wepy.baseToast('获取用户信息失败！')
      }

      // 获取用户登录的凭证 Code
      const loginRes = await wepy.login()
      // console.log(loginRes)
      if (loginRes.errMsg !== 'login:ok') {
        return wepy.baseToast('微信登录失败！')
      }

      // 登录的参数
      const loginParams = {
        code: loginRes.code,
        encryptedData: userInfo.detail.encryptedData,
        iv: userInfo.detail.iv,
        rawData: JSON.stringify(userInfo.detail.rawData),
        signature: userInfo.detail.signature
      }

      // 发起登录的请求，换取登录成功之后的 Token 值
      const { data: res } = await wepy.post('/users/wxlogin', loginParams)
      // console.log(res)
      if (res.meta.status !== 200) {
        return wepy.baseToast('微信登录失败！')
      }

      // 把登录成功之后的 Token 字符串，保存到 Storage 中
      wepy.setStorageSync('token', 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjE1LCJpYXQiOjE1ODIwODMyNjEsImV4cCI6MTAwMTU4MjA4MzI2MH0.7FYQnkt3e4nDBADVUvcZM4SpZmFqM2vFXtHQibs1lAM')
      this.islogin = true
      this.$apply()
    },

    // 支付订单
    async onSubmit() {
      // 1-判断订单状态(商品数量,收货地址)
      if (this.total === 0) {
        return wepy.baseToast('订单商品数量不能为0！')
      }
      if (this.addressStr.length === 0) {
        return wepy.baseToast('请选择收货地址！')
      }

      // 2-创建订单
      const { data: createResult } = await wepy.post('/my/orders/create', {
        order_price: '0.01',
        consignee_addr: this.addressStr,
        order_detail: JSON.stringify(this.orderList),
        goods: this.orderList.map(x => {
          return {
            goods_id: x.id,
            goods_number: x.count,
            goods_price: x.price
          }
        })
      })
      // 创建订单失败
      if (createResult.meta.status !== 200) {
        return wepy.baseToast('创建订单失败！')
      }
      // 创建订单成功
      const orderInfo = createResult.message

      // 3-预支付订单
      const { data: orderResult } = await wepy.post(
        '/my/orders/req_unifiedorder',
        {
          order_number: orderInfo.order_number
        }
      )
      // 生成预支付订单失败
      if (orderResult.meta.status !== 200) {
        return wepy.baseToast('生成预支付订单失败！')
      }

      // 4-支付流程
      const payResult = await wepy.requestPayment(orderResult.message.pay).catch(err => err)
      // 用户取消了支付
      if (payResult.errMsg === 'requestPayment:fail cancel') {
        return wepy.baseToast('您已取消了支付！')
      }

      // 5-检查用户支付状态
      const { data: payCheckResult } = await wepy.post('/my/orders/chkOrder', {
        order_number: orderInfo.order_number
      })
      if (payCheckResult.meta.status !== 200) {
        return wepy.baseToast('订单支付失败！')
      }

      // 提示用户支付成功
      wepy.showToast({
        title: '支付成功！'
      })

      // 跳转到订单列表页面
      wepy.navigateTo({
        url: '/pages/orderlist'
      })
    }
  }

  computed = {
    // 计算是否有地址
    isHaveAddress() {
      if (this.addressInfo === null) {
        return false
      }
      return true
    },
    // 计算收货地址
    addressStr() {
      if (this.addressInfo === null) {
        return ''
      }
      return (
        this.addressInfo.provinceName +
        this.addressInfo.cityName +
        this.addressInfo.countyName +
        this.addressInfo.detailInfo
      )
    },
    // 计算商品总数
    total() {
      return this.$parent.globalData.total
    },
    // 计算商品总价
    amount() {
      let total = 0
      this.orderList.forEach(item => {
        if (item.isCheck) {
          total += item.price * item.count
        }
      })
      return total * 100
    }
  }
}
